#!/bin/sh

RETRY_LIMIT=0
CLUSTER_CRD_NAME=sgcluster
CRD_GROUP=stackgres.io
CLUSTER_NAMESPACE=test
CLUSTER_NAME=test
SERVICE_ACCOUNT=test
POD_NAME=test
CLUSTER_POD_LABELS=app=StackGresCluster,cluster-uid=test,cluster-namespace=test,cluster-name=test
CLUSTER_PRIMARY_POD_LABELS=app=StackGresCluster,cluster-uid=test,cluster-namespace=test,cluster-name=test,role=primary
SHARED_PATH="$TARGET_PATH/$TEST_NAME/shared"
LOCAL_BIN_SHELL_UTILS_PATH="$PROJECT_PATH/src/main/resources/templates/shell-utils"
TIMEOUT=1000000
DBOPS_CRD_NAME=sgdbop.stackgres.io
DBOPS_NAME=test
CONDITION_DBOPS_FALSE_RUNNING='{"lastTransitionTime":"$LAST_TRANSITION_TIME","reason":"OperationNotRunning","status":"False","type":"Running"}'
CONDITION_DBOPS_RUNNING='{"lastTransitionTime":"$LAST_TRANSITION_TIME","reason":"OperationRunning","status":"True","type":"Running"}'
CONDITION_DBOPS_FAILED='{"lastTransitionTime":"$LAST_TRANSITION_TIME","reason":"OperationFailed","status":"True","type":"Failed"}'
CONDITION_DBOPS_TIMED_OUT='{"lastTransitionTime":"$LAST_TRANSITION_TIME","reason":"OperationTimedOut","status":"True","type":"Failed"}'
CONDITION_DBOPS_LOCK_LOST='{"lastTransitionTime":"$LAST_TRANSITION_TIME","reason":"OperationLockLost","status":"True","type":"Failed"}'
CONDITION_DBOPS_FALSE_FAILED='{"lastTransitionTime":"$LAST_TRANSITION_TIME","reason":"OperationNotFailed","status":"False","type":"Failed"}'
CONDITION_DBOPS_COMPLETED='{"lastTransitionTime":"$LAST_TRANSITION_TIME","reason":"OperationCompleted","status":"True","type":"Completed"}'
CONDITION_DBOPS_FALSE_COMPLETED='{"lastTransitionTime":"$LAST_TRANSITION_TIME","reason":"OperationNotCompleted","status":"False","type":"Completed"}'
LOCK_TIMEOUT_KEY=stackgres.io/lockTimeout
LOCK_POD_KEY=stackgres.io/lockPod
RESOURCE_CRD_NAME="$DBOPS_CRD_NAME"
RESOURCE_NAME="$DBOPS_NAME"

shell_unit_test_skip() {
  return 1;
}

shell_unit_test_dbops() {
  rm -rf "$SHARED_PATH"
  mkdir -p "$SHARED_PATH"
  SHARED_PATH="$(realpath "$SHARED_PATH")"

  if command -v shell_unit_test_dbops_init >/dev/null
  then
    shell_unit_test_dbops_init
  fi

  . "$PROJECT_PATH/src/main/resources/templates/set-dbops-running.sh"

  rm -f "$SHARED_PATH/create_event.pipe"
  touch "$SHARED_PATH/create_event.pipe"

  . "$PROJECT_PATH/src/main/resources/templates/run-dbops.sh"

  read_events_service

  . "$PROJECT_PATH/src/main/resources/templates/set-dbops-result.sh"
}

check_dbops_result() {
  EXIT_CODE="$?"
  if [ "$EXIT_CODE" != 0 ]
  then
    return "$EXIT_CODE"
  fi
  if ! grep -q '^EXIT_CODE=[0-9]\+$' "$SHARED_PATH/$KEBAB_OP_NAME.out"
  then
    echo "DbOps terminated without setting EXIT_CODE"
    return 1
  fi
  if ! grep -q '^TIMED_OUT=\(true\|false\)$' "$SHARED_PATH/$KEBAB_OP_NAME.out"
  then
    echo "DbOps terminated without setting TIMED_OUT"
    return 1
  fi
  if ! grep -q '^LOCK_LOST=\(true\|false\)$' "$SHARED_PATH/$KEBAB_OP_NAME.out"
  then
    echo "DbOps terminated without setting LOCK_LOST"
    return 1
  fi
}
